import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import router from 'umi/router';
import {
  Row,
  Col,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Collapse,
  DatePicker,
  PageHeader,
  TreeSelect,
} from 'antd';
import prompt from '@/components/Prompt';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import StandardTable from '@/components/StandardTable';
import AntdSelectRegion from '@/components/AntdSelectRegion';
import SearchSelect from '@/components/SearchSelect';
import { columns1 } from '@/pages/Common/common';
import styles from '@/pages/Operate.less';
import AdButton from '@/components/AdButton';
import { codes } from './utils';

const FormItem = Form.Item;
const { TextArea } = Input;
const { Option } = Select;
const Panel = Collapse.Panel;
const { RangePicker } = DatePicker;
const dateFormat = 'YYYY-MM-DD';
const TreeNode = TreeSelect.TreeNode;
let treeDataGlobal = [];

@connect(({ Location, common, loading }) => ({
  Location,
  ownCompany: common.ownCompany,
  dictObject: common.dictObject,
  id: Location.id,
  loading: loading.models.Location,
}))
@Form.create()
export default class ETCOperate extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedRowKeys: [],
      currentId: '',
      selectedRows: [],
      visible: false,
      activeKey: ['1', '2'],
      showRecord: true, //init:false
      treeValue: [],
      treeRow: {},
      disabled: false,
    };
  }
  componentDidMount() {
    const {
      match,
      form,
      dispatch,
      Location: { locationDetails },
    } = this.props;
    const ID = match && match.params ? match.params.id : '';
    this.setState({
      currentId: ID,
      showRecord: true,
    });
    // this.getLocationList({ id: '44857702471028736' });
    if (ID) {
      // if (locationDetails[ID]) return;
      this.getSelectDetails(ID);
    } else {
      form.resetFields();
    }
  }
  componentWillReceiveProps(nextProps) { }
  //详情信息：
  getSelectDetails = ID => {
    this.props.dispatch({
      type: 'Location/locationDetails',
      payload: { id: ID },
      callback: data => { },
    });
  };

  callback = key => {
    this.setState({
      activeKey: key,
    });
  };

  operatePaneButton = e => {
    e.stopPropagation();
    e.preventDefault();

    this.props.form.validateFields((err, values) => {
      // console.log('values.parentId', values.parentId);
      if (!err) {
        const { parentId, ...value } = values;
        value.parentId =
          parentId.length && parentId.length > 0 ? parentId[parentId.length - 1] : '';
        const {
          match: { params },
          dispatch,
        } = this.props;
        if (params.id) {
          value.id = params.id;
          dispatch({
            type: 'Location/LocationOperate',
            payload: value,
            callback: () => {
              this.setState(preState => ({
                disabled: !preState.disabled,
              }));
              // this.getLocationList({ id: '44857702471028736' });
            },
          });
        } else {
          dispatch({
            type: 'Location/LocationOperate',
            payload: value,
            callback: res => {
              if (!res) return;
              this.setState(preState => ({
                disabled: !preState.disabled,
              }));
              this.setState({ showRecord: true });
              dispatch({
                type: 'Location/locationDetails',
                payload: { id: res },
                callback: data => {
                  //新增变编辑页面：
                  dispatch({
                    type: 'common/setTabsName',
                    payload: {
                      id: res,
                      name: data.adCode,
                      isReplaceTab: true,
                    },
                    callback: result => {
                      if (result) {
                        router.push(`/roadNetwork/locationList/locationEdit/${res}`);
                      }
                    },
                  });
                },
              });
              // this.getLocationList({ id: '44857702471028736' });
            },
          });
        }
      }
    });
  };
  // dispatch 方法
  dispatchFun(type, params) {
    const { dispatch } = this.props;
    dispatch({
      type: type,
      payload: params,
    });
  }
  // 明细查看详情
  showDetail = () => {
    this.setState({ visible: true });
  };

  // 明细关闭详情
  abnormalInfoHandleCancel = () => {
    this.setState({ visible: false, visiblePay: false });
  };

  abledStatus = (e, type) => {
    e.stopPropagation();
    this.child.abledStatus(type);
  };
  handleSelectRows = rows => {
    // console.log('选择', rows);
    let ids = [];
    if (Array.isArray(rows) && rows.length > 0) {
      rows.map((item, i) => {
        ids.push(item.id);
      });
    }
    this.setState({
      selectedRows: rows,
      checkIds: ids,
    });
  };
  //树型区域start：
  getLocationList = (params = {}, type) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'Location/LocationList',
      payload: params,
      callback: res => {
        const { id } = params;
        res.map(v => {
          v.children = [{ address: '-', id: v + '_' + v }];
        });
        if (type == 'child') {
          this.locationData(res, treeDataGlobal, id);
        } else {
          treeDataGlobal = res;
        }
      },
    });
  };
  locationData = (dataChild, data, id) => {
    data.forEach(v => {
      //判断是否有children
      if (v.children.length === 1 && v.children[0].address === '-') {
        if (dataChild.length > 0 && v.id == id) {
          v.children = dataChild;
        }
      } else {
        this.locationData(dataChild, v.children, id);
      }
    });
  };
  onChangeTree = (value, label, extra) => {
    // console.log('(value, label, extra)', value, label, extra);
    // console.log('dataRef', extra.triggerNode.props.dataRef);
    const treeRow = extra.triggerNode.props.dataRef || {};
    this.setState({
      treeRow,
    });
  };
  onTreeExpand = ids => {
    const id = ids[ids.length - 1];
    console.log('ids', ids, 'id', id);
    this.getLocationList({ id }, 'child');
  };

  renderTreeNodes = data =>
    data.map(item => {
      if (item.children) {
        return (
          <TreeNode title={item.address} key={item.id} value={item.id} dataRef={item}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      } else {
        return <TreeNode title={item.address} value={item.id} key={item.id} dataRef={item} />;
      }
    });
  //树型区域end：

  onRef = ref => {
    this.child = ref;
  };

  render() {
    const {
      selectedRowKeys,
      selectedRows,
      visible,
      previewImage,
      fileList,
      papersDetails,
      ownCompany,
      cars,
      showRecord,
      treeValue,
      treeRow,
      currentId,
      disabled,
    } = this.state;
    const {
      Location: { locationDetails, locationDataList },
      form: { getFieldDecorator },
      dictObject,
      match: { params },
      showType,
      loading,
    } = this.props;

    // const currentId = params.id;
    let selectDetails = locationDetails[currentId];
    const checkDisabled = selectDetails ? true : false;

    const vehicleList = [];
    const genExtraBasicInfo = () => (
      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
        <span>{selectDetails && currentId ? selectDetails.adCode : '新增区域'}</span>
        {disabled ? (
          <AdButton
            type="primary"
            onClick={() => {
              this.setState(preState => ({
                disabled: !preState.disabled,
              }));
            }}
            text="编辑"
          />
        ) : (
            <Button.Group>
              <AdButton type="primary" onClick={e => this.operatePaneButton(e)} text="保存" />
              {selectDetails && currentId && (
                <AdButton
                  onClick={() => {
                    this.setState(preState => ({
                      disabled: !preState.disabled,
                    }));
                  }}
                  text="取消"
                />
              )}
            </Button.Group>
          )}
      </div>
    );
    const customPanelStyle = {
      borderRadius: 4,
      marginBottom: 12,
      border: 0,
      overflow: 'hidden',
    };
    const _gutter = { md: 8, lg: 24, xl: 48 };
    const _col = { md: 12, sm: 24 };
    const _row = { md: 24 };

    return (
      <div className={styles.CollapseUpdate}>
        <PageHeaderWrapper title={genExtraBasicInfo()}>
          <Collapse
            activeKey={this.state.activeKey}
            onChange={key => this.callback(key)}
            bordered={false}
          >
            <Panel header="区域信息" key="1" style={customPanelStyle}>
              <div className={styles.tableListForm}>
                <Form layout="inline">
                  <Row gutter={_gutter}>
                    <Col {..._col}>
                      <Form.Item label="上级区域">
                        {getFieldDecorator('parentId', {
                          // rules: [{ required: true, message: '请输入' }],
                          initialValue: selectDetails ? selectDetails.fullParentIds : undefined,
                        })(
                          <AntdSelectRegion
                            url="mds/mds-location-area/selectAreaList"
                            paramsLabel="id"
                            label="address"
                            filter={true}
                            isParent={true}
                            disabled={disabled}
                            split=","
                          />
                        )}
                      </Form.Item>
                    </Col>
                    <Col {..._col}>
                      <Form.Item label="区域代码">
                        {getFieldDecorator('adCode', {
                          rules: [{ required: true, message: '请输入' }],
                          initialValue: selectDetails ? selectDetails.adCode : '',
                        })(
                          <Input
                            placeholder="请输入"
                            disabled={disabled}
                          // disabled={checkDisabled}
                          />
                        )}
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row gutter={_gutter}>
                    <Col {..._col}>
                      <Form.Item label="区域名称">
                        {getFieldDecorator('address', {
                          rules: [{ required: true, message: '请输入' }],
                          initialValue: selectDetails
                            ? selectDetails.address
                            : treeRow
                              ? treeRow.address
                              : '',
                        })(<Input placeholder="请输入" disabled={disabled} />)}
                      </Form.Item>
                    </Col>
                    <Col {..._col}>
                      <Form.Item label="排序号">
                        {getFieldDecorator('sort', {
                          rules: [{ required: true, message: '请输入' }],
                          initialValue: selectDetails
                            ? selectDetails.sort
                            : treeRow
                              ? treeRow.sort
                              : '',
                        })(<Input placeholder="请输入" disabled={disabled} />)}
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row gutter={_gutter}>
                    <Col {..._col}>
                      <Form.Item label="类型">
                        {getFieldDecorator('type', {
                          rules: [{ required: true, message: '请输入' }],
                          initialValue: selectDetails
                            ? selectDetails.type
                            : treeRow
                              ? treeRow.type
                              : '',
                        })(
                          <Select placeholder="请选择" allowClear={true} disabled={disabled}>
                            {/* <Option value="国家">国家</Option> */}
                            <Option value="province">省份直辖市</Option>
                            <Option value="city">地市</Option>
                            <Option value="district">区县</Option>
                          </Select>
                        )}
                      </Form.Item>
                    </Col>
                    <Col {..._col}>
                      <Form.Item label="城市中心点">
                        {getFieldDecorator('center', {
                          rules: [{ required: true, message: '请输入' }],
                          initialValue: selectDetails
                            ? selectDetails.center
                            : treeRow
                              ? treeRow.center
                              : '',
                        })(<Input placeholder="请输入" disabled={disabled} />)}
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row gutter={_gutter}>
                    <Col {..._row}>
                      <Form.Item label="备注">
                        {getFieldDecorator('remarks', {
                          initialValue: selectDetails ? selectDetails.remarks : '',
                        })(<TextArea placeholder="请输入" rows={4} disabled={disabled} />)}
                      </Form.Item>
                    </Col>
                  </Row>
                </Form>
              </div>
            </Panel>
          </Collapse>
        </PageHeaderWrapper>
      </div>
    );
  }
}
